import pandas as pd
import matplotlib.pyplot as plt
import os


def cleancsv(fname):
    # 读取csv文件，假设文件名为data.csv
    df = pd.read_csv(fname)
    # 删除含有"NA"的行
    dfcl = df.drop(df[df.isin(['NA', 'N/A', 'NaN', 'None']).any(1)].index)
    # 将修改后的数据保存到新文件中
    dfcl.to_csv('new_data.csv', index=False)

def addcsv(Folder_Path,SaveFile_Path,SaveFile_Name):
    #要拼接的文件夹及其完整路径
    Folder_Path = r'C:\Users\User\Desktop\code\pycode\python15\PRSA_Data_20130301-20170228' 
    #拼接后要保存的文件路径         
    SaveFile_Path =  r'C:\Users\User\Desktop\code\pycode\python15\PRSA_Data_20130301-20170228'    
    #合并后要保存的文件名   
    SaveFile_Name = r'all.csv'             
    
    #修改当前工作目录
    os.chdir(Folder_Path)
    #将该文件夹下的所有文件名存入一个列表
    file_list = os.listdir()
    
    #读取第一个CSV文件并包含表头
    df = pd.read_csv(Folder_Path +'\\'+ file_list[0])   #编码默认UTF-8，若乱码自行更改
    
    #将读取的第一个CSV文件写入合并后的文件保存
    df.to_csv(SaveFile_Path+'\\'+ SaveFile_Name,encoding="utf_8_sig",index=False)
    
    #循环遍历列表中各个CSV文件名，并追加到合并后的文件
    for i in range(1,len(file_list)):
        df = pd.read_csv(Folder_Path + '\\'+ file_list[i])
        df.to_csv(SaveFile_Path+'\\'+ SaveFile_Name,encoding="utf_8_sig",index=False, header=False, mode='a+')


class DataAnalysis():
    #创建类变量
    file_path = "C:/Users/User/Desktop/code/pycode/python15/PRSA_Data_20130301-20170228/"   
    all_csv = "all.csv" 
    #创建含有时间的csv文件
    def addtime(self,station):
        fname="PRSA_Data_"+station+"_20130301-20170228.csv"
        data = pd.read_csv(DataAnalysis.file_path+fname) # 读取CSV格式的数据文件
        columns = data.columns.tolist() # 获取数据文件中所有的列名
        # 将 'year'、'month'、'day' 和 'hour' 列合并成一个时间戳列 'time'
        data['time'] = pd.to_datetime({'year': data['year'], 'month': data['month'], 'day': data['day'], 'hour': data['hour']})

        # 将 'time' 列移动到第一列
        cols = data.columns.tolist()
        cols = cols[-1:] + cols[:-1]
        data = data[cols]

        # 写入CSV文件
        data.to_csv(station+'.csv', index=False)
    
    def temporal_analysis(self,station,measure_type,start_index,end_index):
        # 筛选出污染物类型的数据
        df=pd.read_csv(station+'.csv')
        time_range = df['time'][start_index:end_index+1]
        # 筛选出指定时间范围内的数据
        data = df.loc[df['time'].isin(time_range)]
        data1 = data[['time',measure_type]]
        plt.plot(data1['time'], data1[measure_type])
        #将x轴时间点旋转90度
        plt.xticks(data1.time, rotation=90)
        # 显示x轴标识:
        plt.xlabel('time')
        #显示y轴标识
        plt.ylabel('content')
        plt.title(f'{station}')
        plt.tight_layout()
        plt.show()
        
    def space_analysis_point(self,measure_type,year,month,day,hour):
        data = pd.read_csv(DataAnalysis.file_path+DataAnalysis.all_csv) # 读取CSV格式的数据文件
        condition1 = data['year'] == year
        condition2 = data['month'] == month
        condition3 = data['day'] == day
        condition4 = data['hour'] == hour
        condition = condition1&condition2&condition3&condition4
        result = data[condition]
        newname=f"时间点{year}_{month}_{day}_{hour}.csv"
        result.to_csv(newname,mode="a")
        dfnew = pd.read_csv(newname)
        x=dfnew['station']
        y=dfnew[f'{measure_type}']
        plt.bar(x, y)
        plt.xlabel('station')
        plt.ylabel('content')
        plt.xticks(dfnew.station, rotation=90)
        plt.tight_layout()
        plt.show()
        
        
if __name__ =="__main__":
    print("What do you want to do?")
    answer=input("temporal_analysis(1)/space_analysis_point(2):")
    if answer=="1":
        stationtest = input('''请输入检测地点名,从以下12个地点选择一个复制粘贴
(Aotizhongxin/Changping/Dingling/Dongsi/Guanyuan/Gucheng/
Huairou/Nongzhanguan/Shunyi/Tiantan/Wanliu/Wanshouxigong):''')
        measuretype = input('''请输入测量名,从以下12个指标选择一个复制粘贴
(PM2.5/PM10/SO2/NO2/CO/O3/TEMP/PRES/DEWP/RAIN/wd/WSPM):''')
        # 创建DataAnalysis对象
        data_analysis = DataAnalysis()
        datanew = data_analysis.addtime(stationtest)
        # 展示某区域某类型污染物随时间的变化
        data_analysis.temporal_analysis(stationtest,measuretype,0,24*1)
    elif answer=="2":
        measuretype = input('''请输入测量名,从以下12个指标选择一个复制粘贴
(PM2.5/PM10/SO2/NO2/CO/O3/TEMP/PRES/DEWP/RAIN/wd/WSPM):''')
        print("请输入年月日小时：",end="")
        year,month,day,hour=map(int,input().split())
        # 创建DataAnalysis对象
        data_analysis = DataAnalysis()
        # 展示某区域某类型污染物随时间的变化
        data_analysis.space_analysis_point(measuretype,year,month,day,hour)
